package cn.edu.niit.dao;

import cn.edu.niit.db.JDBCUtil;
import cn.edu.niit.javabean.Announcement;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class AnnouncementDao {
    public List<Announcement> getAllAnnouncement(int pageNum, int pageSize) {
        String sql = "select * from announcement order by publish_date desc limit ?,?";
        List<Announcement> list = new ArrayList<>();
        try {
            ResultSet rs = JDBCUtil.getInstance().executeQueryRS(sql, new Object[]{(pageNum - 1) * pageSize,
                    pageSize});
            while (rs.next()) {
                Announcement announcement = Announcement.builder().id(rs.getString("id")).detail(rs.getString("detail"))
                        .publishDate(rs.getTimestamp("publish_date")).title(rs.getString("title")).build();
                list.add(announcement);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return list;
    }

    public int getAllAnnouncementCount() {
        String sql = "select count(0) as countNum from announcement";
        try {
            ResultSet rs = JDBCUtil.getInstance().executeQueryRS(sql, new Object[]{});
            while (rs.next()) {
               return rs.getInt("countNum");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 0;
    }
}
